<?php
namespace app\xiaohongshu\service;

use app\common\model\xiaohongshu\Author;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class XhsService
{
    protected $baseUrl = '';

    protected $url = '/base_info/';
    protected $client;


    public function __construct($apiKey = null)
    {
        $this->baseUrl = config('site.xiaohongshu_collect_url');
        // dump($this->baseUrl);
        $this->client = new Client(['base_uri' => $this->baseUrl]);

    }

    /**
     * 查询用户笔记信息
     *
     * @param string $userId 用户ID
     * @return array|false 返回用户笔记信息或错误信息
     */
    public function getUserInfo($uuid)
    {
        try {
            $response = $this->client->get($this->url . $uuid);

            if ($response->getStatusCode() == 200) {
                $data = json_decode($response->getBody()->getContents(), true);
                
                // 查找是否存在该作者
                $author = Author::where('uuid', $uuid)->find();
                
                $saveData = [
                    'uuid' => $uuid,
                    'signature' => $data['Signature_field'] ?? '',
                    'avatar' => $data['avatar'] ?? '',
                    'collect_like' => $data['collect_like'] ?? '',
                    'fans_num' => $data['fans_num'] ?? '',
                    'gender' => $data['gender'] ?? '',
                    'ip_address' => $data['ip_address'] ?? '',
                    'nickname' => $data['nick_name'] ?? '',
                    'redbook_id' => $data['redbook_id'] ?? '',
                ];

                if ($author) {
                    // 存在则更新
                    $author->save($saveData);
                } else {
                    // 不存在则创建
                    Author::create($saveData);
                }
                
                return $data;
            } else {
                return false;
            }
        } catch (RequestException $e) {
            return false;
        }
    }

   
    public function analyzeUrl($url)
    {
        // Define the URL pattern to capture the user ID from the Xiaohongshu profile URL
        $pattern = '/\/user\/profile\/([a-zA-Z0-9]+)/';

        // Use regular expression to match and extract the user ID from the URL
        if (preg_match($pattern, $url, $matches)) {
            $id = $matches[1];
            return $id;
        }

        // Return null if the ID could not be extracted
        return null;
    }

}
